/* eslint-disable eqeqeq */
/* eslint-disable no-dupe-keys */
/* eslint-disable no-mixed-spaces-and-tabs */
/* eslint-disable no-tabs */

<template>
  <div style="background: #eff1f4; width: 98%; height: 96%; margin: 2% 2% 2% 0%;">
    <el-row :gutter="10" style="height: 50%">
      <div id="lineChart_1" :style="{width: '100%', height: '100%'}" />
    </el-row>
    <el-row :gutter="10" style="margin-top: 20px; height: 45%">
      <el-col :span="10" style="height: 100%">
        <div id="lineChart_2" :style="{width: '100%', height: '100%'}" />
      </el-col>
      <el-col :span="14" style="height: 100%">
        <div id="table" :style="{width: '100%', height: '100%'}">
          <span style="text-align: left;width: 100%;height: 100%;font-weight: bold;">近期写入的数据</span>
          <el-table ref="singleTable" :data="tableData" border :max-height="tableHeight" size="small" style="width: 100%;height: 100%;margin-top: 20px;" highlight-current-row :show-header="true">
            <el-table-column prop="index" label=" " align="center" min-width="20" />
            <el-table-column prop="mertic" label="mertic" min-width="50" />
            <el-table-column prop="value" label="值" min-width="40" />
            <el-table-column prop="time" label="时间" min-width="70" />
            <el-table-column prop="tags" label="标签" min-width="100" />
          </el-table>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// import axios from 'axios'
import { formatTime } from '@/utils/util.js'
import axiosservice from '@/utils/CommonData.js'
import { formatDate } from '@/utils/time.js'
// 在组件引入基本模板
import * as echarts from 'echarts'
import resize from './mixins/resize'
// 在组件引入柱状图组件
require('echarts/lib/chart/bar')
require('echarts/lib/chart/pie')
require('echarts/lib/chart/line')
export default {
  name: 'Echarts',
  data() {
    return {
      tableHeight: window.innerHeight * 0.45 - 80,
      mixins: [resize],
      timer: null,
      colorArray: ['#3499DD', '#70AD46', '#C59F46', '#E7505A', '#32C5D3', '#8F44AD', '#CB660A', '#A7B7CC', '#3499DD', '#32C5D3', '#E7505A', '#C59F46', '#8F44AD', '#70AD46', '#CB660A', '#A7B7CC'],
      tableData: [],
      line1: null,
      line2: null
    }
  },
  mounted() {
    console.log(this.tableHeight)
    this.line1 = echarts.init(document.getElementById('lineChart_1'))
    this.line2 = echarts.init(document.getElementById('lineChart_2'))
    this.init()
    this.UpdateData()
    this.timer = setInterval(this.UpdateData, 5000)
    window.addEventListener('resize', () => {
      // console.log(this.tableHeight)
      this.tableHeight = window.innerHeight * 0.45 - 80
      // console.log(this.tableHeight) // ；两次值确实不一样，用于el-table resize
    })
  },
  beforeDestroy() {
    echarts.dispose(this.line1)
    echarts.dispose(this.line2)
    clearInterval(this.timer)
    this.timer = null
  },
  methods: {
    init() {
      const xData1 = ['15:21:57', '15:21:58', '15:21:59', '15:22:00', '15:22:01', '15:22:02', '15:22:03', '15:22:04', '15:22:05', '15:22:06', '15:22:07', '15:22:08', '15:22:09', '15:22:10', '15:22:11', '15:22:12', '15:22:13', '15:22:14', '15:22:15', '15:22:16', '15:22:17', '15:22:18', '15:22:19', '15:22:20', '15:22:21', '15:22:22', '15:22:23', '15:22:24', '15:22:25', '15:22:26', '15:22:27', '15:22:28', '15:22:29', '15:22:30', '15:22:31', '15:22:32', '15:22:33', '15:22:34', '15:22:35', '15:22:36', '15:22:37', '15:22:38', '15:22:39', '15:22:40', '15:22:41', '15:22:42', '15:22:43', '15:22:44', '15:22:45', '15:22:46', '15:22:47', '15:22:48', '15:22:49', '15:22:50', '15:22:51', '15:22:52', '15:22:53', '15:22:54', '15:22:55', '15:22:56', '15:22:57', '15:22:58', '15:22:59', '15:23:00', '15:23:01']
      const data1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 990.0989990234375, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
      this.lineDraw(this.line1, '实时写入速度（条/秒）', xData1, data1)
      const xData2 = ['15:26:51', '15:27:01', '15:27:11', '15:27:19', '15:27:22', '15:27:34', '15:27:44', '15:27:45', '15:27:54', '15:27:55']
      const data2 = [1, 1, 1, 2, 2, 2, 1, 1, 1, 1]
      this.lineDraw(this.line2, '网络连接个数', xData2, data2)
    },
    UpdateData() {
      this.UpdateLine1()
      // this.UpdateLine2()
      // this.UpdateTable()
    },
    UpdateLine1() {
      axiosservice.get('/writespeed')
        .then((res) => {
          // eslint-disable-next-line eqeqeq
          if (res.status == 200) {
            const avg = res.data.avg
            // console.log(avg)
            const result = res.data.data
            console.log(res.data)
            var data = []
            var avgdata = []
            var xData = []
            for (var key in result) {
              const keyNew = formatDate(new Date(key * 1000), 'hh:mm:ss')
              xData.push(keyNew)
              data.push(result[ key ]) // 注意是 [  ]
              avgdata.push(avg)
            }
            // console.log(xData.length)
            if (xData.length > 60) {
              xData = xData.slice(0, 60)// 多于60个只保留前60个
              data = data.slice(0, 60)
              avgdata = data.slice(0, 60)
            }
            // console.log('hou' + xData.length)
            // this.lineDraw('lineChart_1', '实时写入速度（条）', xData, data)
            this.refreshData1(this.line1, xData, data, avgdata)
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('实时写入速度接口调用失败!')
        })
    },
    UpdateLine2() {
      axiosservice.get('/api/state')
        .then((res) => {
          // eslint-disable-next-line eqeqeq
          if (res.status == 200) {
            const data = []
            const xData = []
            const result = res.data// .replace("[","{").replace("]","}");
            // let d =  eval('(' + result + ')');

            for (var i = 0; i < result.length; i++) {
              for (var key in result[i]) {
                const keyNew = formatDate(new Date(key * 1000), 'hh:mm:ss')
                xData.push(keyNew)
                data.push(result[i][ key ]) // 注意是 [  ]
              }
            }
            // console.log(xData)
            // console.log(data)
            // this.lineDraw('lineChart_2', '设备链接个数', xData, data)
            this.refreshData(this.line2, xData, data)
          }
        })
        .catch((error) => {
          console.log(error)
          // this.$message.error('设备链接个数接口调用失败!')
        })
    },
    refreshData1(echart, xData, data, avgdata) {
      // 刷新数据
      var option = echart.getOption()
      // console.log(option)
      const newxAxis = {
        type: 'category',
        boundaryGap: false,
        data: xData,
        axisLabel: {
          interval: 0,
          rotate: 40
        },
        textStyle: {
          fontSize: 8
        }
      }
      option.xAxis = newxAxis
      option.series[0].data = data
      if (option.series[1]) {
        option.series[1].data = avgdata
      } else {
        option.series.push({
          name: '平均写入速度（条/秒）',
          type: 'line',
          data: avgdata
        })
      }
      echart.setOption(option, true)
      echart.resize()
    },
    refreshData(echart, xData, data) {
      // 刷新数据
      var option = echart.getOption()
      // console.log(option)
      const newxAxis = {
        type: 'category',
        boundaryGap: false,
        data: xData,
        axisLabel: {
          interval: 0,
          rotate: 40
        },
        textStyle: {
          fontSize: 8
        }
      }
      option.xAxis = newxAxis
      option.series[0].data = data
      echart.setOption(option, true)
      echart.resize()
    },

    lineDraw(echart, title, xData, data) {
      // 基于准备好的dom，初始化echarts实例
      // echarts.dispose(document.getElementById(id))
      const line = echart
      // 绘制图表配置
      const option = {
        color: this.colorArray,
        title: {
          text: title
          // subtext: '此处可加子标题'
        },
        grid: {
          top: 45,
          bottom: 50,
          left: 50,
          right: 10
        },
        tooltip: {
          trigger: 'axis'
        },
        toolbox: {
          show: true,
          feature: {
            dataZoom: {
              yAxisIndex: 'none'
            },
            dataView: { readOnly: false },
            magicType: { type: ['line', 'bar'] },
            restore: {},
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xData,
          axisLabel: {
            interval: 0,
            rotate: 40
          },
          textStyle: {
            fontSize: 8
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            type: 'value',
            formatter: '{value}',
            // formatter: function(value, index) {
            //   return parseInt(value)
            // },
            minInterval: 1
          }
        },
        series: [
          {
            name: title,
            type: 'line',
            data: data,
            smooth: true
            // areaStyle: {},
            /* markPoint: {
                      data: [
                          {type: 'max', name: '最大值',itemStyle:{color:'#E7505A'}},
                          {type: 'min', name: '最小值',itemStyle:{color:'#70AD46'}}
                      ]
                  },

                  markLine: {
                      data: [
                        {type: 'average', name: '平均值'}
                      ]
                  } */
          }
        ]
      }
      // 窗口大小自适应方案
      line.setOption(option)
      // setTimeout(function() {
      //   window.onresize = function() {
      //     line.resize()
      //   }
      // }, 200)
      window.addEventListener('resize', () => {
        line.resize()
      })
    },
    UpdateTable() {
      axiosservice.get('/writingdata')// http://jbz.sqflash.com:8080/
        .then((res) => {
          // debugger;
          // eslint-disable-next-line eqeqeq
          if (res.status == 200) {
            const data = res.data.data
            // console.log(this.tableData)
            this.tableData = []
            for (var index in data) {
              // console.log(index, data[index])
              const linelist = data[index].slice(1, -1).split(',').splice(1)
              // console.log(linelist.slice(3).toString())
              this.tableData.push({
                'index': parseInt(index) + 1,
                'mertic': linelist[0],
                'time': formatTime(parseInt(linelist[1]) * 1000),
                'value': linelist[2],
                'tags': linelist.slice(3).toString()
              })
            }
          }
        })
        .catch((error) => {
          console.log(error)
          // this.$message.error('调用近期写入数据的metrics接口失败!')
        })
    }
  }
}

</script>
